package com.cisystem.web.controller.business;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cisystem.common.core.domain.entity.SysDept;
import com.cisystem.common.utils.StringUtils;
import com.cisystem.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cisystem.common.annotation.Log;
import com.cisystem.common.core.controller.BaseController;
import com.cisystem.common.core.domain.AjaxResult;
import com.cisystem.common.enums.BusinessType;
import com.cisystem.system.domain.GoodCatch;
import com.cisystem.system.service.IGoodCatchService;
import com.cisystem.common.utils.poi.ExcelUtil;
import com.cisystem.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * GoodCatchController
 *
 * @author kelly
 * @date 2023-07-08
 */
@RestController
@RequestMapping("/business/goodCatch")
public class GoodCatchController extends BaseController {
    @Autowired
    private IGoodCatchService goodCatchService;

    @Autowired
    ISysDeptService deptService;
    /**
     * 查询GoodCatch列表
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(GoodCatch goodCatch) {
        startPage();
        List<GoodCatch> list = goodCatchService.selectGoodCatchList(goodCatch);
        return getDataTable(list);
    }

    /**
     * 导出GoodCatch列表
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:export')")
    @Log(title = "GoodCatch", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodCatch goodCatch) {
        List<GoodCatch> list = goodCatchService.selectGoodCatchList(goodCatch);
        // deptId 转化成描述
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        Map<String,String> deptDes = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysDepts)){
            deptDes = sysDepts.stream().collect(Collectors.toMap(i->String.valueOf(i.getDeptId()),
                    SysDept::getDeptName,(f, b)->f));
        }
        // feasibility 转化
        Map<String,String> feasibilityMap  = new HashMap<>();
        feasibilityMap.put("1","Yes");
        feasibilityMap.put("2","No");
        feasibilityMap.put("3","Padding");
        // 状态转化
        Map<String,String> statusMap  = new HashMap<>();
        statusMap.put("1","Open");
        statusMap.put("2","Ongoing");
        statusMap.put("3","Closed");
        for (GoodCatch aCatch : list) {
            aCatch.setDeptId(deptDes.get(aCatch.getDeptId()));
            aCatch.setFeasibility(feasibilityMap.get(aCatch.getFeasibility()));
            aCatch.setStatus(statusMap.get(aCatch.getStatus()));
            // 设置owner的部门
            String ownerHistory = aCatch.getOwnerHistory();
            if (!StringUtils.isEmpty(ownerHistory)){
                try {
                    JSONArray array = JSONArray.parseArray(ownerHistory);
                    JSONObject jsonObject = array.getJSONObject(array.size() - 1);
                    JSONObject owner = jsonObject.getJSONObject("owner");
                    String deptId = owner.getString("deptId");
                    aCatch.setOwnerDept(deptDes.get(deptId));
                }catch (Exception e){
                    logger.error("goodcatch转化owner历史json出错",e);
                }
            }
        }
        ExcelUtil<GoodCatch> util = new ExcelUtil<GoodCatch>(GoodCatch.class);
        util.exportExcel(response, list, "GoodCatch数据");
    }

    /**
     * 获取GoodCatch详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(goodCatchService.selectGoodCatchById(id));
    }

    /**
     * 新增GoodCatch
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:add')")
    @Log(title = "GoodCatch", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodCatch goodCatch) {
        return toAjax(goodCatchService.insertGoodCatch(goodCatch));
    }

    /**
     * 修改GoodCatch
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:edit')")
    @Log(title = "GoodCatch", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GoodCatch goodCatch) {
        return toAjax(goodCatchService.updateGoodCatch(goodCatch));
    }

    /**
     * 删除GoodCatch
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:remove')")
    @Log(title = "GoodCatch", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(goodCatchService.deleteGoodCatchByIds(ids));
    }

    /**
     * 批量reclosed  GoodCatch
     */
    @PreAuthorize("@ss.hasPermi('business:goodCatch:reconfirm')")
    @Log(title = "GoodCatch", businessType = BusinessType.DELETE)
    @GetMapping("/reClosed/{ids}")
    public AjaxResult reconfirm(@PathVariable Long[] ids) {
        return toAjax(goodCatchService.reClosedGoodCatchByIds(ids));
    }

    @Log(title = "GoodCatch", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('business:goodCatch:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<GoodCatch> util = new ExcelUtil<>(GoodCatch.class);
        List<GoodCatch> list = util.importExcel(file.getInputStream());
        // deptId 转化成描述
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        Map<String,String> deptDes = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysDepts)){
            deptDes = sysDepts.stream().collect(Collectors.toMap(SysDept::getDeptName,i->String.valueOf(i.getDeptId()),(f, b)->f));
        }
        // feasibility 转化
        Map<String,String> feasibilityMap  = new HashMap<>();
        feasibilityMap.put("Yes","1" );
        feasibilityMap.put("No","2");
        feasibilityMap.put("Padding","3");
        // 状态转化
        Map<String,String> statusMap  = new HashMap<>();
        statusMap.put("Open","1");
        statusMap.put("Ongoing","2");
        statusMap.put("Closed","3");
        for (GoodCatch goodCatch : list) {
            goodCatch.setDeptId(deptDes.get(goodCatch.getDeptId()));
            goodCatch.setFeasibility(feasibilityMap.get(goodCatch.getFeasibility()));
            goodCatch.setStatus(statusMap.get(goodCatch.getStatus()));
        }
        String operName = getUsername();
        String message = goodCatchService.importGoodCatch(list, updateSupport, operName);
        return success(message);
    }
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<GoodCatch> util = new ExcelUtil<GoodCatch>(GoodCatch.class);
        util.importTemplateExcel(response, "GoodCatch");
    }
}
